import { Component, OnInit } from '@angular/core';
import {DaAPI} from '../../da-constants';
import {TokenUtil} from '../../../../util/token-util';
import {ActivatedRoute, Router} from '@angular/router';
import {MsgConstants} from '../../../../constants/constants';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {PageSubject} from '../../../../util/page-subject';

declare var Dropzone;

@Component({
  selector: 'app-da-vocs-file-upload',
  templateUrl: './da-vocs-file-upload.component.html',
  styleUrls: ['./da-vocs-file-upload.component.css']
})
export class DaVocsFileUploadComponent implements OnInit {
  myDropzone: any;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: OneDialogService,
    private pageSubject: PageSubject,
    private tokenUtil: TokenUtil
  ) { }

  ngOnInit() {
    this.initDropzone();
    this.pushPage();
  }
  pushPage() {
    // const path = new Path('数据矫正', '');
    this.pageSubject.pushPage('数据校正', '数据上传');
  }
  initDropzone() {
    const siteCode = this.route.snapshot.params['siteCode'];
    const deviceCode = this.route.snapshot.params['deviceCode'];
    const monitorTime = this.route.snapshot.params['monitorTime'];
    this.myDropzone = new Dropzone('#myId', {
      url: DaAPI.daVOCsFileUpload + '?sitecode=' + siteCode + '&devicecode=' + deviceCode + '&monitortime=' + monitorTime,
      headers: {
        Authorization:  'Bearer ' + this.tokenUtil.getToken()
      },
      // maxFiles: 1,
      acceptedFiles: '.txt',
      autoProcessQueue: false,
      dictDefaultMessage: '拖动文件至此或者点击上传',
      dictMaxFilesExceeded: '您最多只能上传1个文件！',
      dictResponseError: '文件上传失败!',
      dictInvalidFileType: '文件类型只能是.txt格式文件',
      dictFallbackMessage: '浏览器不受支持',
      dictFileTooBig: '文件过大上传文件最大支持.',
      dictRemoveLinks: '删除',
      dictCancelUpload: '取消',
    });
    this.myDropzone.on('addedfile', () => {
      const queuedFiles = this.myDropzone.getQueuedFiles();
      if (queuedFiles.length > 0) {
        this.myDropzone.removeFile(queuedFiles[0]);
      }
    });
    this.myDropzone.on('success', (file , result) => {
      if (result && result.code === MsgConstants.MSG_CODE_OK) {
        if (result.code === MsgConstants.MSG_CODE_OK) {
          this.dialogService.success('文件：' + file.name + '上传成功');
          this.cancelSubmit();
        } else {
          this.dialogService.info(result.message);
        }
      }
      if (result && result.code !== MsgConstants.MSG_CODE_OK) {
        this.dialogService.info(result.message);
      }
    });
  }
  cancelSubmit() {
    this.myDropzone.removeAllFiles();
    this.router.navigate(['..'], {relativeTo: this.route})
  }
  submit() {
    this.myDropzone.processFiles(this.myDropzone.getQueuedFiles());
  }
}
